package cn.com.klun.tjy.other.ThreadsTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TouTiaoMST {
    /**
     * 头条一则面试题
     * 题目：启动两个线程向文件temp.txt中写入递增的数字
     * 线程1先写入 thread-1，thread-2，thread-3，thread-4，thread-5，
     * 然后是线程2 再写入thread-6，thread-7，thread-8，thread-9，thread-10，
     * 接着再由线程1写入thread-11，thread-12，thread-13，thread-14，thread-15
     * 以此类推，知道打印到50，程序为
     */
    public static void main(String[] args) {
        Wk wk = new Wk();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(new ThA(wk));
        executorService.execute(new ThB(wk));
        executorService.shutdown();
        try {
            executorService.awaitTermination(300, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
//做共享内存锁
class Wk{
    private int i = 1;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    public Boolean getFlag() {
        return flag;
    }
    private void setFlag(Boolean flag) {
        this.flag = flag;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    private Boolean flag;
    //自增的方法
    public void incrA(String name ,int count){
        lock.lock();
        try {
            while ((i/5)%2 == 1) {
                for (int j = 0; j < 5; j++) {
                    Thread.sleep(100);
                    System.out.println(name + "-" + i++);
                }
                condition.wait();
            }
            //循环完成叫醒另外一个
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void incrB(String name ,int count){
        lock.lock();
        try {
            while ((i/5)%2 == 0) {
                for (int j = 0; j < 5; j++) {
                    Thread.sleep(100);
                    System.out.println(name + "-" + i++);
                }
                condition.wait();
            }
            //循环完成叫醒另外一个
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
//使用重入锁
class ThA extends Thread{
    private Wk wk;
    public ThA(Wk wk){
        this.wk = wk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 25; i++) {
            wk.incrA("ThreadA",0);
        }
    }
}
class ThB extends Thread{
    private Wk wk;
    public ThB(Wk wk){
        this.wk = wk;
    }
    @Override
    public void run() {
        for (int i = 0; i < 25; i++) {
            wk.incrB("ThreadB",0);
        }

    }
}